<?php
/**
 * 上传图片
*/
class upload
{
	private $dataDir;
	public function __construct($dir)
	{
		if ( !empty($dir) )
		{
			$this->dataDir = $dir . '/data';
		} else {
			$this->dataDir = dirname(__FILE__).'/data';
		}
	}
	
	public function __destruct()
	{
		
	}
	
	/**
	 * 上传图片
	 * @params key 		string File控件名称
	 * @params maxSize 	int    最大字节数
	 * @return array
	*/
	public function add($key, $maxSize = 204800)
	{
		$extensions = array(
			IMAGETYPE_GIF => "gif",
			IMAGETYPE_JPEG => "jpg",
			IMAGETYPE_PNG => "png",
			IMAGETYPE_SWF => "swf",
			IMAGETYPE_PSD => "psd",
			IMAGETYPE_BMP => "bmp",
			IMAGETYPE_TIFF_II => "tiff",
			IMAGETYPE_TIFF_MM => "tiff",
			IMAGETYPE_JPC => "jpc",
			IMAGETYPE_JP2 => "jp2",
			IMAGETYPE_JPX => "jpx",
			IMAGETYPE_JB2 => "jb2",
			IMAGETYPE_SWC => "swc",
			IMAGETYPE_IFF => "iff",
			IMAGETYPE_WBMP => "wbmp",
			IMAGETYPE_XBM => "xbm",
			IMAGETYPE_ICO => "ico"
		);
		$data = array( 'code'=>'001', 'msg'=>'上传的文件不存在!' );
		if ( isset( $_FILES[$key] ) )
		{
			$data = array( 'code'=>'002', 'msg'=>'文件上传失败!' );
			$error 	 = $_FILES[$key]['error'];
			if ( $error === 0 )
			{
				$size 	 = $_FILES[$key]['size'];
				// 防止传入非法参数
				$maxSize = (int) $maxSize;
				($maxSize<=0) && $maxSize = 204800;
				if( $size > $maxSize )
				{
					$data = array('code'=>'003', 'msg'=>'文件大小超过限制，最大'. floor( $maxSize/1024 ) .'K!');
				} else {
					$whiteFileTypes = array(
						'image/jpeg',
						'image/pjpeg',
						'image/gif',
						'image/png',
						'image/x-png',
						'image/bmp'
					);
					$fileType= $_FILES[$key]['type'];
					$data = array( 'code'=>'004', 'msg'=>'上传的文件不是支持的类型!' );
					if ( in_array( $fileType, $whiteFileTypes ) )
					{
						$tmpFile = $_FILES[$key]['tmp_name'];
						$data = file_get_contents($tmpFile);
						$tmpFile= getimagesize($tmpFile);
						@unlink($tmpFile);
						$width   = $tmpFile[0];
						$height  = $tmpFile[1];
						$type 	 = $extensions[$tmpFile[2]];
						$fileName = md5($data) .'.'. $type;
						$p1 = substr($fileName, 0, 2); // 目录1
						$p2 = substr($fileName, 2, 2); // 目录2
						$dir = sprintf('%s/%s/%s', $this->dataDir, $p1, $p2); // 目录
						$filePath = sprintf('%s/%s', $dir, $fileName); // 文件路径
						is_dir($dir) || @mkdir( $dir, 0777, true );// 创建目录
						
						$fp = fopen($filePath, 'wb');
						fwrite($fp, $data);
						fclose($fp);
						$data = array( 'code'=>'005', 'msg'=>'系统繁忙!' );
						if ( file_exists($filePath) )
						{
							$data = array( 'code'=>'000', 'msg'=>'文件上传成功!', 'uri'=>$filePath, 'width'=>$width, 'height'=>$height );
						}
					}
				}
			}
		}
		return $data;
	}
	
	public function del()
	{
		
	}
	
}